//
//  KKChatMessageTableViewCell.m
//  ReplyAssistant
//
//  Created by liaozhenming on 2018/11/21.
//  Copyright © 2018 KK. All rights reserved.
//

#import "KKChatMsgTableViewCells.h"
#import "KKMessageItem.h"

#import "FBKVOController.h"
#import "KKImageBrowser.h"

#import "KCLabel.h"

#pragma mark - KKChatTextMessageCell methods
@implementation KKChatTextMessageCell

//  加入内容控件
- (UIView*)addElemContent {
    _lab_messageText = [[KCLabel alloc] initWithFrame: CGRectZero];
    _lab_messageText.font = [UIFont systemFontOfSize: 15];
    _lab_messageText.numberOfLines = 0;
    _lab_messageText.lineBreakMode = NSLineBreakByCharWrapping;
    _lab_messageText.allowCopy = true;
    return _lab_messageText;
}

- (void)configContent {
    [super configContent];
    
    RAMessage *item = self.msg.msg;
    if ([item isKindOfClass: [RATextMessage class]]) {
        RATextMessage *tmpItem = (RATextMessage*)item;
        
        NSDictionary *attributeDict = [NSDictionary dictionaryWithObjectsAndKeys: [UIFont systemFontOfSize: 15], NSFontAttributeName,[UIColor blackColor], NSForegroundColorAttributeName,nil];
        
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString: @""];
        NSAttributedString *string = [[NSAttributedString alloc]initWithString: tmpItem.content attributes: attributeDict];
        [attributedString appendAttributedString: string];
        
        _lab_messageText.attributedText = attributedString;
    }
    
    if (self.msg.isMineMsg) {
        _lab_messageText.textColor = [UIColor whiteColor];
    }
    else {
        _lab_messageText.textColor = [UIColor darkGrayColor];
    }
}

@end


#pragma mark - KKChatTimeTipsMessageCell methods

@implementation KKChatTimeTipsMessageCell

- (instancetype)initWithC2CReuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle: UITableViewCellStyleDefault reuseIdentifier: reuseIdentifier];
    if (self) {
        [self private_initMessageCell];
    }
    return self;
}

- (void)configContent {
    [super configContent];
    
    RAMessage *msg = self.msg.msg;
    self.textLabel.text = [msg.timeDate timeTextOfDate];
}

#pragma mark - Private methods
- (void)private_initMessageCell {
    self.contentView.backgroundColor = [UIColor clearColor];
    self.backgroundColor = [UIColor clearColor];
    self.textLabel.textAlignment = NSTextAlignmentCenter;
    self.textLabel.lineBreakMode = NSLineBreakByWordWrapping;
    self.textLabel.numberOfLines = 1;
    self.textLabel.font = [UIFont systemFontOfSize:12];
    self.textLabel.textColor = [UIColor colorWithHexString: @"aaaaaa"];
}

@end

#pragma mark - KKChatTimeTipsMessageCell methods

@interface KKChatImageMessageCell()

@property (nonatomic, strong) FBKVOController *progressKVO;           // 会话的KVO

@end

@implementation KKChatImageMessageCell

//  加入内容控件
- (UIView*)addElemContent {
    _img_message = [[UIImageView alloc] init];
    
    _coveringView = [[UIView alloc] initWithFrame: _img_message.bounds];
    _coveringView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    _coveringView.backgroundColor = [UIColor colorWithWhite: 0.0 alpha: 0.25];
    
    {
        CGFloat width = CGRectGetWidth(_coveringView.bounds);
        
        _progress = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle: UIActivityIndicatorViewStyleWhite];
        _progress.center = CGPointMake(width/2.0, CGRectGetHeight(_coveringView.bounds)/2.0);
        _progress.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        [_progress startAnimating];
        [_coveringView addSubview: _progress];
        
        _lab_progress = [[UILabel alloc] initWithFrame: CGRectMake(0, 0, width, 15)];
        _lab_progress.center = CGPointMake(width/2.0, CGRectGetHeight(_coveringView.bounds)/2.0 + 10);
        _lab_progress.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        _lab_progress.textColor = [UIColor whiteColor];
        _lab_progress.font = [UIFont systemFontOfSize: 13];
        _lab_progress.textAlignment = NSTextAlignmentCenter;
        [_coveringView addSubview: _lab_progress];
        _coveringView.hidden = true;
    }
    
    [_img_message addSubview: _coveringView];
    
    //  设置图片视图接收点击事件
    _img_message.userInteractionEnabled = true;
    UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget: self action: @selector(on_Tap:)];
    [_img_message addGestureRecognizer: recognizer];
    
    return _img_message;
}

- (void)configContent {
    [super configContent];
    
    RAMessage *item = self.msg.msg;
    if ([item isKindOfClass: [RAImageMessage class]]) {
        RAImageMessage *tmpItem = (RAImageMessage*)item;
        
        [self configKVO];
        
        if (tmpItem.image != nil) {
            _img_message.image = tmpItem.image;
        }
        else if (tmpItem.imgPath != nil) {
            __weak RAImageMessage* weakImageMessage = tmpItem;
            __weak typeof(self) weakSelf = self;
            _coveringView.hidden = false;
            NSURLRequest *request = [[NSURLRequest alloc] initWithURL: [NSURL URLWithString: tmpItem.imgPath]];
            [_img_message setImageWithURLRequest: request placeholderImage: nil success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull image) {
                weakImageMessage.image = image;
                weakSelf.img_message.image = image;
                weakSelf.coveringView.hidden = true;
            } failure: nil];
        }
    }
}

- (void)configKVO {
    
    if (self.msg.status != KKMessageStatus_Sending) {
        //  表示正在发送中则监听上传进度
        return;
    }
    
    RAMessage *item = self.msg.msg;
    if ([item isKindOfClass: [RAImageMessage class]]) {
        RAImageMessage *tmpItem = (RAImageMessage*)item;
        [_progressKVO unobserveAll];
        if (!_progressKVO){
            _progressKVO = [FBKVOController controllerWithObserver:self];
        }
        __weak typeof(self) weakSelf = self;
        _coveringView.hidden = false;
        [_progress startAnimating];
        
        [_progressKVO observe: tmpItem keyPath:@"progress" options:NSKeyValueObservingOptionNew block:^(id observer, id object, NSDictionary *change) {
            
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                weakSelf.lab_progress.text = [NSString stringWithFormat: @"%0.f%%", tmpItem.progress * 100];
                weakSelf.coveringView.hidden = tmpItem.progress == 1.0 ? true : false;
            }];
        }];
    }
}

#pragma mark - Action methods
- (void)on_Tap:(UITapGestureRecognizer*)tapper {
    
    RAMessage *item = self.msg.msg;
    if ([item isKindOfClass: [RAImageMessage class]]) {
        RAImageMessage *tmpItem = (RAImageMessage*)item;
        
        if (tmpItem.image != nil) {
            [KKImageBrowser kk_showImagesWithImages: @[tmpItem.image]];
        }
        else {
            [KKImageBrowser kk_showImagesWithPaths: @[tmpItem.imgPath]];
        }
    }
}

@end
